<?php

namespace app\store\service;

use app\store\model\GoodsCategory;
use think\facade\Db;

class GoodsCategoryService
{

    public function getCategoryList($keyword)
    {
        $model = new GoodsCategory();

        $query = $model->withOutField('desc');

        if(!empty($keyword)){
            $query->whereLike('name',"%$keyword%");
        }

        $categories = $query->select();
        
        return  !$categories->isEmpty() ? generateTreeOption($categories->toArray()) : [];
        
    }

    public function findCategory($id)
    {
        $model = new GoodsCategory();
        $category = $model->withOutField('create_time,update_time')->find($id);
    
        
        return $category;
        
    }

    public function getCategoryOption($fliter = false)
    {
        $model = new GoodsCategory();
        $query = $model->field('id,parent_id,name,path');

        if($fliter){
            $query->where('status',1);
        }

        $categories = $query->select();
        
        return  !$categories->isEmpty() ? generateTreeOption($categories->toArray()) : [];
        
    }

    // 查询是否有子分类

    public function categorySonExsits($id)
    {   
        $model = new GoodsCategory();
        $sonCategory =$model->field('id')->where('parent_id',$id)->find();

        return !empty($sonCategory) ? true : false; 
    }

    public static function saveGoodsCategory($data)
    {
        if ($data['parent_id']){
            $path = Db::name('goods_category')->where('id',$data['parent_id'])->value('path');
            $joinPath = $path.'-'.$data['parent_id'];
            $data['path'] = $joinPath;
        } else {
            $data['path'] = $data['parent_id'];
        }

       $category =  GoodsCategory::create($data);

       return $category['id'];
    }



}